package demo1;

import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;

/**
 * @description: 查询操作
 * @author: apple
 * @date:  2022/1/9 5:18 下午
 * @version 1.0
 **/
public class QueryTest {


    public Student query(String sql , Object...params) throws SQLException, IOException, NoSuchFieldException, IllegalAccessException {
         Connection connection = null;
         PreparedStatement preparedStatement = null;
         ResultSet resultSet = null;
        try {
            connection = JDBCUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }
            resultSet = preparedStatement.executeQuery();
            // 拿到结果集的元数据，用于获取表的列数等信息
            final ResultSetMetaData metaData = resultSet.getMetaData();
            final int columnCount = metaData.getColumnCount();
            System.out.println("列的数量："+columnCount);
            if (resultSet.next()) {
                System.out.println("开始填充对象的数据");
                Student student = new Student();
                for (int i = 0; i < columnCount; i++) {
                    final Object columnValue = resultSet.getObject(i + 1);
                    // 获取列的列名，但获取不了列的别名
                    final String columnName = metaData.getColumnName(i + 1);
                    // 调用student对象的columnName列，设置为columnValue
                    final Field f1 = Student.class.getDeclaredField(columnName);
                    f1.setAccessible(true);
                    f1.set(student,columnValue);
                }
                return student;
            }

        } finally {
            JDBCUtil.closeConnection(connection,preparedStatement,resultSet);
        }

        return null;
    }



    @Test
    public void test1() throws SQLException, IOException, NoSuchFieldException, IllegalAccessException {

        String sql = "select * from student where name = ?";
        final Student query = query(sql , "小红");
        System.out.println(query);

    }
}
